package com.muqi.app.qlearn.student.ui;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.apache.http.Header;
import org.apache.http.NameValuePair;
import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicNameValuePair;
import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.muqi.app.network.http.NetWorkUtils;
import com.muqi.app.pay.zhifubao.AliPayContants;
import com.muqi.app.pay.zhifubao.PayResult;
import com.muqi.app.pay.zhifubao.SignUtils;
import com.muqi.app.project.contants.NetWorkApi;
import com.muqi.app.project.utils.LogUtil;
import com.muqi.app.project.utils.ShowToast;
import com.muqi.app.qlearn.modles.PayOrderId;
import com.muqi.app.qlearn.student.BaseFragmentActivity;
import com.muqi.app.qlearn.student.R;
import com.muqi.app.qlearn.student.wxapi.WXPayEntryActivity;
import com.muqi.app.qlearn.student.wxapi.WePayConstants;
import com.muqi.app.qlearn.student.wxapi.WePayUtils;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.wenhui.pedant.SweetAlert.SweetAlertDialog;
import com.wenhui.pedant.SweetAlert.SweetAlertDialog.OnSweetClickListener;

public class MoneyPayActivity extends BaseFragmentActivity implements OnClickListener {
	public static final String PAY_WITH_SUCCESS = "pay_with_success";
	public static final String TAG = MoneyPayActivity.class.getSimpleName();
	public static final int RESULT_CODE_WORDS = 2001;
	private static final int SDK_PAY_FLAG = 1;
	private static final int SDK_CHECK_FLAG = 2;
	private static final int ZHIFUBAO = 1;
	private static final int WEIXIN = 2;
	private int mPayType = ZHIFUBAO;
	
	private Button payNowBtn;
	private TextView mOrderId;
	private TextView mOrderMoney;
	private RadioGroup payWays;
	
	private PayOrderId mPayOrderInfo;
	private String alipay_notify_url = NetWorkApi.SERVER_IP + "common/payment/ali_mobVipNotify/";
	private String wx_notify_url = NetWorkApi.SERVER_IP +"common/payment/weixin_mobVipNotify";
	private Map<String, String> resultunifiedorder;
	private PayReq req;  // 微信支付相关的类
	final IWXAPI msgApi = WXAPIFactory.createWXAPI(this, null);
	
	
	@SuppressLint("HandlerLeak") 
	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case SDK_PAY_FLAG: {
				PayResult payResult = new PayResult((String) msg.obj);
				// 支付宝返回此次支付结果及加签，建议对支付宝签名信息拿签约时支付宝提供的公钥做验签
				// String resultInfo = payResult.getResult();
				String resultStatus = payResult.getResultStatus();
				// 判断resultStatus 为“9000”则代表支付成功
				if (TextUtils.equals(resultStatus, "9000")) {
					paySuccess();
				} else {
					// 判断resultStatus 为非“9000”则代表可能支付失败
					// “8000”代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
					if (TextUtils.equals(resultStatus, "8000")) {

					} else if (TextUtils.equals(resultStatus, "6001")) {
						payNowBtn.setEnabled(true);
					} else if (TextUtils.equals(resultStatus, "6002")) {
						payNowBtn.setEnabled(true);
					} else {
						// 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
						payNowBtn.setEnabled(true);
					}
				}
				break;
			}
			default:
				break;
			}
		};
	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.aty_money_pay);
		registerPayBroadCast();
	}
	
	private PaySuccessReceiver receiver;
	private void registerPayBroadCast() {
		receiver = new PaySuccessReceiver();
		IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(WXPayEntryActivity.PAY_WITH_SUCCESS);
        intentFilter.addAction(WXPayEntryActivity.PAY_WITH_FAILE);
        registerReceiver(receiver, intentFilter);
	}
	
    private class PaySuccessReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(WXPayEntryActivity.PAY_WITH_SUCCESS)) {
               MoneyPayActivity.this.finish();
            }else if(action.equals(WXPayEntryActivity.PAY_WITH_FAILE)){
            	MoneyPayActivity.this.finish();
            }
        }
    }
    
    @Override
    protected void onDestroy() {
    	super.onDestroy();
    	unregisterReceiver(receiver);
    }
    
    
	@Override
	protected void onInit() {
		req = new PayReq();
		msgApi.registerApp(WePayConstants.APP_ID);

		mOrderId = (TextView) findViewById(R.id.pay_order_id);
		mOrderMoney = (TextView) findViewById(R.id.pay_money);
		payWays = (RadioGroup)findViewById(R.id.pay_way_group);
		payWays.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			
			@Override
			public void onCheckedChanged(RadioGroup group, int checkedId) {
				switch (checkedId) {
				case R.id.pay_with_zhifubao:
					mPayType = ZHIFUBAO;
					break;
				case R.id.pay_with_weixin:
					mPayType = WEIXIN;
					break;
				default:
					break;
				}
			}
		});
		payNowBtn = (Button) findViewById(R.id.pay_btn);
		payNowBtn.setOnClickListener(this);
	}

	@Override
	protected void onData() {
		mPayOrderInfo = (PayOrderId) getIntent().getSerializableExtra("item");
		if(mPayOrderInfo!=null){
			mOrderId.setText(mPayOrderInfo.out_trade_no);
			mOrderMoney.setText("￥"+mPayOrderInfo.totalfee);
		}else{
			finish();
		}
	}
	
	private void paySuccess() {
		Intent intent = new Intent();
		intent.setAction(PAY_WITH_SUCCESS);
		sendBroadcast(intent);
		
		finish();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.pay_btn:
			if(mPayType == ZHIFUBAO){
				payWithZhifubao();
			}else if( mPayType == WEIXIN){
				payByWeiXin();
			}
			break;
		default:
			break;
		}
	}
	
	/************************************************************************************************/
	 
	private void payWithZhifubao() {
		String payMoney = mPayOrderInfo.totalfee;
		if (TextUtils.isEmpty(payMoney)) {
			payMoney = "0.01";
		}
		payMoney = "0.01";
		// 订单
		String orderInfo = getOrderInfo("悦成长", "会员充值", payMoney);
		// 对订单做RSA 签名
		String sign = sign(orderInfo);
		try {
			// 仅需对sign 做URL编码
			sign = URLEncoder.encode(sign, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		// 完整的符合支付宝参数规范的订单信息
		final String payInfo = orderInfo + "&sign=\"" + sign + "\"&" + getSignType();

		Runnable payRunnable = new Runnable() {

			@Override
			public void run() {
				// 构造PayTask 对象
				PayTask alipay = new PayTask(MoneyPayActivity.this);
				// 调用支付接口，获取支付结果
				String result = alipay.pay(payInfo);
				Message msg = new Message();
				msg.what = SDK_PAY_FLAG;
				msg.obj = result;
				mHandler.sendMessage(msg);
			}
		};
		// 必须异步调用
		Thread payThread = new Thread(payRunnable);
		payThread.start();
	}

	/**
	 * check whether the device has authentication alipay account.
	 * 查询终端设备是否存在支付宝认证账户
	 * 
	 */
	public void check(View v) {

		Runnable checkRunnable = new Runnable() {

			@Override
			public void run() {
				// 构造PayTask 对象
				PayTask payTask = new PayTask(MoneyPayActivity.this);
				// 调用查询接口，获取查询结果
				boolean isExist = payTask.checkAccountIfExist();

				Message msg = new Message();
				msg.what = SDK_CHECK_FLAG;
				msg.obj = isExist;
				mHandler.sendMessage(msg);
			}
		};

		Thread checkThread = new Thread(checkRunnable);
		checkThread.start();
	}

	/**
	 * get the sdk version. 获取SDK版本号
	 * 
	 */
	public void getSDKVersion() {
		PayTask payTask = new PayTask(this);
		String version = payTask.getVersion();
		Toast.makeText(this, version, Toast.LENGTH_SHORT).show();
	}

	/**
	 * create the order info. 创建订单信息
	 * 
	 */
	public String getOrderInfo(String subject, String body, String price) {
		// 签约合作者身份ID
		String orderInfo = "partner=" + "\"" + AliPayContants.PARTNER + "\"";
		// 签约卖家支付宝账号
		orderInfo += "&seller_id=" + "\"" + AliPayContants.SELLER + "\"";
		// 商户网站唯一订单号
		orderInfo += "&out_trade_no=" + "\"" + getOutTradeNo() + "\"";
		// 商品名称
		orderInfo += "&subject=" + "\"" + subject + "\"";
		// 商品详情
		orderInfo += "&body=" + "\"" + body + "\"";
		// 商品金额
		orderInfo += "&total_fee=" + "\"" + price + "\"";
		// 服务器异步通知页面路径
		orderInfo += "&notify_url=" + "\"" + alipay_notify_url + "\"";
		// 服务接口名称， 固定值
		orderInfo += "&service=\"mobile.securitypay.pay\"";
		// 支付类型， 固定值
		orderInfo += "&payment_type=\"1\"";
		// 参数编码， 固定值
		orderInfo += "&_input_charset=\"utf-8\"";

		// 设置未付款交易的超时时间
		// 默认30分钟，一旦超时，该笔交易就会自动被关闭。
		// 取值范围：1m～15d。
		// m-分钟，h-小时，d-天，1c-当天（无论交易何时创建，都在0点关闭）。
		// 该参数数值不接受小数点，如1.5h，可转换为90m。
		orderInfo += "&it_b_pay=\"30m\"";

		// extern_token为经过快登授权获取到的alipay_open_id,带上此参数用户将使用授权的账户进行支付
		// orderInfo += "&extern_token=" + "\"" + extern_token + "\"";

		// 支付宝处理完请求后，当前页面跳转到商户指定页面的路径，可空
		orderInfo += "&return_url=\"m.alipay.com\"";

		// 调用银行卡支付，需配置此参数，参与签名， 固定值 （需要签约《无线银行卡快捷支付》才能使用）
		// orderInfo += "&paymethod=\"expressGateway\"";

		return orderInfo;
	}

	/**
	 * get the out_trade_no for an order. 生成商户订单号，该值在商户端应保持唯一（可自定义格式规范）
	 * 
	 */
	public String getOutTradeNo() {
		String key = mPayOrderInfo.out_trade_no;
		return key;
	}

	/**
	 * sign the order info. 对订单信息进行签名
	 * 
	 * @param content
	 *            待签名订单信息
	 */
	public String sign(String content) {
		return SignUtils.sign(content, AliPayContants.RSA_PRIVATE);
	}

	/**
	 * get the sign type we use. 获取签名方式
	 * 
	 */
	public String getSignType() {
		return "sign_type=\"RSA\"";
	}
	
/**************************************以上是支付宝支付过程***************************************************/
	
	private void payByWeiXin() {
		showLoading();
		if (NetWorkUtils.isNetworkAvailable(this)) {
			try {
				// 生成预支付的交易订单
				String xml = genProductArgs();
				StringEntity entity = new StringEntity(xml);
				String url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
				new AsyncHttpClient().post(this, url, entity,
						"application/json", new AsyncHttpResponseHandler() {

							@Override
							public void onFailure(int arg0, Header[] arg1,
									byte[] arg2, Throwable arg3) {
								showToast("error");
							}

							@Override
							public void onSuccess(int arg0, Header[] arg1,
									byte[] data) {
								String content = new String(data);
								Log.e("===", "微信后台结果payactivity" + content);
								Map<String, String> xml = WePayUtils.decodeXml(content);
								resultunifiedorder = xml;
								genPayReq();
								sendPayReq();
							}

						});
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} else {
			ShowToast.showShort(this, R.string.net_break);
		}
	}
	
	private void genPayReq() {
		req.appId = WePayConstants.APP_ID;
		req.partnerId = WePayConstants.MCH_ID;
		req.prepayId = resultunifiedorder.get("prepay_id");
		req.packageValue = "Sign=WXPay";
		req.nonceStr = WePayUtils.genNonceStr();
		req.timeStamp = String.valueOf(WePayUtils.genTimeStamp());

		List<NameValuePair> signParams = new LinkedList<NameValuePair>();
		signParams.add(new BasicNameValuePair("appid", req.appId));
		signParams.add(new BasicNameValuePair("noncestr", req.nonceStr));
		signParams.add(new BasicNameValuePair("package", req.packageValue));
		signParams.add(new BasicNameValuePair("partnerid", req.partnerId));
		signParams.add(new BasicNameValuePair("prepayid", req.prepayId));//+req.prepayId));
		signParams.add(new BasicNameValuePair("timestamp", req.timeStamp)); 

		req.sign = WePayUtils.genAppSign(signParams);

		LogUtil.e("调起微信请求参数："+signParams.toString());
	}
	
	
	private void sendPayReq() {
		hideLoading();
		boolean f = msgApi.sendReq(req);
		if(f){
			Log.e("===","请求微信成功");
		}else{
			Toast.makeText(mContext, "请求微信失败", Toast.LENGTH_SHORT).show();
			Log.e("===","请安装微信在支付");
		}
	}
	
	private String genProductArgs() {
		StringBuffer xml = new StringBuffer();
		try {
			String nonceStr = WePayUtils.genNonceStr(); // 随机的一个字符串
			int orderMoney = 0;
			try{
				orderMoney = Integer.valueOf(mPayOrderInfo.totalfee.trim())*100;
			}catch(Exception e){
				LogUtil.e(TAG+"钱数转换异常"+e.toString());
			}
//			String money = mPayOrderInfo.totalfee;
			String money = String.valueOf(orderMoney);
			Log.e("===", money);

			xml.append("</xml>");
			List<NameValuePair> packageParams = new LinkedList<NameValuePair>();

			packageParams.add(new BasicNameValuePair("appid",WePayConstants.APP_ID));
			packageParams.add(new BasicNameValuePair("body", "会员充值"));
			packageParams.add(new BasicNameValuePair("mch_id",WePayConstants.MCH_ID));
			packageParams.add(new BasicNameValuePair("nonce_str", nonceStr));
			packageParams.add(new BasicNameValuePair("notify_url",wx_notify_url));
			packageParams.add(new BasicNameValuePair("out_trade_no",mPayOrderInfo.out_trade_no));
			packageParams.add(new BasicNameValuePair("spbill_create_ip","127.0.0.1"));
			//TODO 设置钱数
			packageParams.add(new BasicNameValuePair("total_fee", money));
//			packageParams.add(new BasicNameValuePair("total_fee", "1"));
			packageParams.add(new BasicNameValuePair("trade_type", "APP"));

			String sign = WePayUtils.genPackageSign(packageParams);
			packageParams.add(new BasicNameValuePair("sign", sign));

			String xmlstring = WePayUtils.toXml(packageParams);

			return new String(xmlstring.toString().getBytes(), "ISO8859-1");

		} catch (Exception e) {
			// Log.e(TAG, "genProductArgs fail, ex = " + e.getMessage());
			return null;
		}
	}

	public void onBack(View v){
		new SweetAlertDialog(this, SweetAlertDialog.WARNING_TYPE)
		.setTitleText("还未支付,确认放弃支付吗？")
		.setCancelText("取消")
		.setConfirmText("确定")
		.showCancelButton(true)
		.setCancelClickListener(new OnSweetClickListener() {
			@Override
			public void onClick(SweetAlertDialog mDialog) {
				mDialog.dismissWithAnimation();
			}
		})
		.setConfirmClickListener(new OnSweetClickListener() {
			@Override
			public void onClick(SweetAlertDialog mDialog) {
				MoneyPayActivity.this.finish();
			}
		}).show();
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
	}
	
}
